from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from geetest import GeetestLib
from blog import models, forms
from django.contrib import messages
from django.urls import reverse
import datetime
import os


# Create your views here.

def login(request):
    if request.method == 'POST':
        # 初始化一个给AJAX返回的数据
        ret = {"status": 0, "msg": ""}
        # 从提交过来的数据中 取到用户名和密码
        username = request.POST.get("username")
        pwd = request.POST.get("password")
        # 获取极验 滑动验证码相关的参数
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        status = request.session[gt.GT_STATUS_SESSION_KEY]
        user_id = request.session["user_id"]

        if status:
            result = gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        if result:
            # 验证码正确
            # 利用auth模块做用户名和密码的校验
            user = auth.authenticate(username=username, password=pwd)
            if user:
                # 用户名密码正确
                # 给用户做登录
                auth.login(request, user)
                ret["msg"] = reverse('index')
            else:
                # 用户名密码错误
                ret["status"] = 1
                ret["msg"] = "用户名或密码错误！"
        else:
            ret["status"] = 1
            ret["msg"] = "验证码错误"

        return JsonResponse(ret)

    return render(request, 'login.html')


pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"


# 处理极验 获取验证码的视图
def get_geetest(request):
    user_id = 'test'
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    status = gt.pre_process(user_id)
    request.session[gt.GT_STATUS_SESSION_KEY] = status
    request.session["user_id"] = user_id
    response_str = gt.get_response_str()
    return HttpResponse(response_str)


def index(request):
    # 查询所有的文章列表
    article_list = models.Article.objects.all()

    return render(request, "index.html", {"article_list": article_list})


def reg(request):
    form_obj = forms.RegForm

    if request.method == 'POST':
        form_obj = forms.RegForm(request.POST)
        if form_obj.is_valid():
            avatar_img = request.FILES.get('avatar')
            # 效验通过
            form_obj.cleaned_data.pop('re_password')  # 从表单中删除数据库不需要的字段
            models.UserInfo.objects.create_user(avatar=avatar_img, **form_obj.cleaned_data)
            messages.success(request, '注册成功，请登陆')
            return redirect('login')
        else:
            messages.warning(request, '验证失败')
    return render(request, 'register.html', {
        'form_obj': form_obj
    })


def blog_info(request, blog_name):
    pass


@login_required
def logout(request):
    auth.logout(request)
    messages.success(request, '安全退出')
    return redirect('login')
